<?php 
class Core_YouTube
{
    protected static $_youtube;
    
    private static function _getCache()
    {
        return YouNet_Util::getObjectFileCache();
    }
    
    public static function _initYouTubeObject() {
        self::$_youtube = Zend_Registry::getInstance()->get('youtube_object');
		self::$_youtube->setMajorProtocolVersion(2);
    }
    
    public static function getEmbedVideo($yt_video_id)
    {
        $url = '<iframe class="video_display" style="width: 510px; height: 350px; margin: 0 5px;" src="http://www.youtube.com/embed/' . $yt_video_id .'?wmode=transparent" frameborder="0" allowfullscreen></iframe>';
        return $url;
    }
    
    public static function getVideoId($video_url)
	{
        $purl = parse_url($video_url);
        if (isset($purl['query']))
        {
            parse_str($purl['query'], $video_code);
            if (isset($video_code['v']))
            {
                return $video_code['v'];
            }
        }
        return '';
	}
    
    public static function getUser($url)
	{
		$expr = '/youtube\.com\/user\/([\w\d-_]+)/';
        $flat = preg_match($expr, $url, $matches);
        if ($flat == 1)
        {
            return $matches[1];
        }
        else
        {
            return '';
        }
        
	}
    
    public static function getVideoEntryInfo($videoEntry) 
    {
        $title          = $videoEntry->getVideoTitle();
        $yt_video_id    = $videoEntry->getVideoId();
        $update_time    = $videoEntry->getUpdated();
        $description    = $videoEntry->getVideoDescription();
        $category       = $videoEntry->getVideoCategory();
        $tags           = implode(", ", $videoEntry->getVideoTags());
        $url            = $videoEntry->getVideoWatchPageUrl();
        $flash_url      = $videoEntry->getFlashPlayerUrl();
        $duration       = $videoEntry->getVideoDuration();
        $view_count     = $videoEntry->getVideoViewCount();
        $rating         = $videoEntry->getVideoRatingInfo();
        $location       = $videoEntry->getVideoGeoLocation();
        $thumbnail      = self::getFirstThumbnail($videoEntry->getVideoThumbnails());

        $videoEntryInfo = array(
            'title'         => $title,
            'yt_video_id'   => $yt_video_id,
            'update_time'   => $update_time,
            'description'   => $description,
            'category'      => $category,
            'tags'          => $tags,
            'url'           => $url,
            'flash_url'     => $flash_url,
            'duration'      => $duration,
            'view_count'    => $view_count,
            'rating'        => $rating,
            'location'      => $location,
            'thumbnail'     => $thumbnail
        );
        
        return $videoEntryInfo;
    }
    
    public static function getFirstThumbnail($videoThumbnails)
    {
        if (count($videoThumbnails) > 0)
        {
            return $videoThumbnails[0]['url'];
        }
        return 'http://s.ytimg.com/yt/img/no_thumbnail-vfl4t3-4R.jpg';
    }
    
    public static function getVideoEntryById($yt_video_id)
    {
        self::_initYouTubeObject();
        try{
            return self::$_youtube->getVideoEntry($yt_video_id);
        }  catch (Exception $e)
        {
            return null;
        }
    }
    
    public static function getVideoEntryInfoById($yt_video_id)
    {
        $videoEntry = self::getVideoEntryById($yt_video_id);
        if(!empty($videoEntry))
        {
            return self::getVideoEntryInfo($videoEntry);
        }
        return null;
    }

    public static function getVideoFeedInfo($videoFeed)
    {
        $videoFeedInfo = array();
        foreach ($videoFeed as $videoEntry)
        {
            $videoFeedInfo[] = self::getVideoEntryInfo($videoEntry);
        }
        return $videoFeedInfo;
    }

    public static function getVideoFeedByUrl($url)
    {
        self::_initYouTubeObject();
        return self::$_youtube->getVideoFeed($url);
    }
    
    public static function getPlaylistVideos($playlist_id)
    {
        $cache = self::_getCache();
        $playlist_key = 'YouTube_Playlist_' . $playlist_id;
        $videoFeedInfo = $cache->load($playlist_key);
        if($videoFeedInfo === false)
        {
            $gdata_url = 'http://gdata.youtube.com/feeds/api/playlists/' . $playlist_id . '?v=2';
            $feed_url = self::getVideoFeedByUrl($gdata_url);
            $videoFeedInfo = self::getVideoFeedInfo($feed_url);
            $cache->save($videoFeedInfo, $playlist_key, array(), LIFETIME_CACHE);
        }
        return $videoFeedInfo;
    }
    
    public static function getChannelVideos($channel_url)
    {
        $username = self::getUser($channel_url);
        if (!empty($username))
        {
            $gdata_url = 'http://gdata.youtube.com/feeds/api/users/' . $username . '/uploads?v=2';
            $feed_url = self::getVideoFeedByUrl($gdata_url);
            return self::getVideoFeedInfo($feed_url);
        }
        return array();
    }
    
    public static function getVideoEntryInfoByUrl($video_url)
    {
        $yt_video_id = self::getVideoId($video_url);
        if (!empty($yt_video_id))
        {
            $videoEntry = self::getVideoEntryById($yt_video_id);
            if (!empty($videoEntry))
            {
                return self::getVideoEntryInfo($videoEntry);
            }
        }
        return null;
    }
}
